<?php
class Core_Component_Sef_Business_Rewrite_Rewriter_Regex extends Core_Component_Sef_Business_Rewrite_Rewriter_Base{

	private $_outputRules = array();
	private $_routeRules = array();
	
	public function addOutputRule($sPattern, $rPattern, $rDomain = 'www', $sDomain = 'www'){
		$this->_outputRules[] = array('sPattern'=>$sPattern, 'rPattern'=>$rPattern, 'sDomain'=>$sDomain, 'rDomain'=>$rDomain);
		return $this;
	}
	
	public function addRouteRule($sPattern, $rPattern, $rDomain = 'www', $sDomain = 'www'){
		$this->_routeRules[] = array('sPattern'=>$sPattern, 'rPattern'=>$rPattern, 'sDomain'=>$sDomain, 'rDomain'=>$rDomain);
		return $this;
	}	

	public function rewriteOutput(&$input, &$output){
		foreach($input as $index=>$url){
			foreach($this->_outputRules as $rule){
				$urlRegex = '/'.str_replace('.', '\.', 'http:\/\/'.$rule['sDomain'].'.'.DN).$rule['sPattern'].'/i';
				if(preg_match($urlRegex, $url, $match)){
					$u = Soul_Util_String::format($rule['rPattern'], $match);
					$u = preg_replace('/\{\d+\}/i', '', $u);
					if(substr($u, -1) == '/'){
						$u = substr($u, 0, -1);
					}
					$output[$url] = 'http://'.$rule['rDomain'].'.'.DN.$u.'.html';
					unset($input[$index]);
					break;
				}
			}
		}
	}
	
	public function rewriteRoute($url){
		$subdomain = $GLOBALS[RC]->getRequest()->getSubdomain();
		foreach($this->_routeRules as $rule){
			if($subdomain == $rule['rDomain'] && preg_match('/'.$rule['sPattern'].'/i', $url, $match)){
				return array('domain'=>$rule['sDomain'], 'url'=>Soul_Util_String::format($rule['rPattern'], $match));
			}
		}
		return FALSE;
	}	
}